package com.phonebook.controller;

import com.phonebook.constant.JwtConstant;
import com.phonebook.entity.Admin;
import com.phonebook.entity.CheckResult;
import com.phonebook.entity.ResponseResult;
import com.phonebook.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

/**
 * 刷新token
 *
 * @author Administrator
 */
@RestController
@RequestMapping("token")
@Api(tags = "tokenApi")
public class TokenController {

    private final Logger logger = LoggerFactory.getLogger(TokenController.class);

    /**
     * 刷新用户token
     *
     * @param token
     * @return
     */
    @ApiOperation("刷新用户token")
    @ApiImplicitParam(name = "token", value = "token", dataTypeClass = Admin.class, required = true, paramType = "header")
    @GetMapping(value = "refreshToken")
    public ResponseResult refreshToken(@RequestHeader String token) {
        CheckResult jwtCheckResult = JwtUtils.validateJWT(token);
        if(!jwtCheckResult.isSuccess()){
            return ResponseResult.error(jwtCheckResult.getErrCode(),jwtCheckResult.getMessage());
        }
        Claims claims = jwtCheckResult.getClaims();
        String newToken = JwtUtils.createJWT(claims.getId(), claims.getSubject(), JwtConstant.JWT_TTL);
        logger.info("新token:" + newToken);
        return ResponseResult.success(new HashMap<String,Object>(16){{ put("token", newToken); }});
    }
}
